package com.sunnyebuy.merchant.action;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import au.com.bytecode.opencsv.CSVReader;

import com.opensymphony.xwork2.ModelDriven;
import com.sunnyebuy.merchant.SystemConfig;
import com.sunnyebuy.merchant.action.model.CustomerOrderModel;
import com.sunnyebuy.merchant.po.CustomerOrder;
import com.sunnyebuy.merchant.po.CustomerOrderProductDetail;
import com.sunnyebuy.merchant.po.CustomerOrderShippingAddress;
import com.sunnyebuy.merchant.service.CustomerOrderService;
import com.sunnyebuy.merchant.status.PaymentStatus;

/**
 * <p>
 * Title: CustomerOrderAction.java
 * </p>
 * 
 * <p>
 * Description: com.sunnyebuy.merchant.action
 * </p>
 * 
 * <p>
 * Copyright: Copyright (c) 2008-2011 All rights reserved.
 * </p>
 * 
 * <p>
 * Created: 2011-12-30 下午4:45:23
 * </p>
 * 
 * @author Wenzhong Gu
 * 
 * @version 1.0
 */
@Controller(value = "customerOrderAction")
@Scope(value = "prototype")
public class CustomerOrderAction extends MerchantBaseAction implements ModelDriven<CustomerOrderModel> {

	private static final long serialVersionUID = 2579737606465430650L;

	Logger log = LoggerFactory.getLogger(CustomerOrderAction.class);

	private CustomerOrderModel model = new CustomerOrderModel();
	private List<CustomerOrder> orderList;

	@Resource
	private CustomerOrderService customerOrderService;

	public String importFile() {
		log.info("===into importFile===");
		String directory = SystemConfig.ORDER_UPLOAD_FILE_PATH;
		String targetDirectory = ServletActionContext.getServletContext().getRealPath(directory);
		String fileName = getSession().get(SystemConfig.MERCHANT_ID_SESSION_NAME) + "-" + model.getUploadFileName();
		File target = new File(targetDirectory, fileName);
		if (target.exists()) {
			target.delete();
		}
		try {
			FileUtils.copyFile(model.getUpload(), target);
			// csv文件，以逗号分隔
			if (fileName.toLowerCase().endsWith("csv")) {
				CSVReader reader = new CSVReader(new FileReader(target), ',');
				// 第一行为标题头，跳过
				reader.readNext();
				String[] csvRow; // 行
				List<CustomerOrder> orders = new ArrayList<CustomerOrder>();
				CustomerOrder order;
				CustomerOrderShippingAddress address;
				while ((csvRow = reader.readNext()) != null) {
					order = new CustomerOrder();
					address = new CustomerOrderShippingAddress();
					// 发票号
					String invoiceNO = csvRow[0];
					order.setInvoiceNo(invoiceNO);
					// 交易号
					String tradeNO = csvRow[1];
					order.setTradeNo(tradeNO);
					// 收货人名字
					String firstName = csvRow[2];
					address.setCustomerFirstName(firstName);
					// 收货人姓氏
					String lastName = csvRow[3];
					address.setCustomerLastName(lastName);
					// 收货人电话
					String phone = csvRow[4];
					address.setCustomerPhone(phone);
					// 运输方式
					String shipType = csvRow[5];
					order.setShippingType(shipType);
					// 国家
					String country = csvRow[6];
					address.setCustomerCountry(country);
					// 省/州
					String state = csvRow[7];
					address.setCustomerState(state);
					// 城市
					String city = csvRow[8];
					address.setCustomerCity(city);
					// 街道1
					String street1 = csvRow[9];
					address.setCustomerStreet1(street1);
					// 街道2
					String street2 = csvRow[10];
					address.setCustomerStreet2(street2);
					// 邮编
					String postCode = csvRow[11];
					address.setCustomerPostcode(postCode);
					int rowLength = csvRow.length;
					CustomerOrderProductDetail productDetail;
					List<CustomerOrderProductDetail> productDetails = new ArrayList<CustomerOrderProductDetail>();
					for (int p = 6; p * 2 < rowLength; p++) {
						productDetail = new CustomerOrderProductDetail();
						// 产品标识
						String sku = csvRow[p * 2];
						productDetail.setMerchantProductSku(sku);
						// 产品数量
						String num = csvRow[p * 2 + 1];
						productDetail.setProductCount(Integer.parseInt(num));
						productDetails.add(productDetail);
					}
					order.setCustomerOrderProductDetails(productDetails);
					order.setCustomerOrderShippingAddress(address);
					orders.add(order);
				}
				customerOrderService.addCustomerOrders(orders);
				reader.close();
			}
			// excel文件
			else if (fileName.toLowerCase().endsWith("xls")) {
				Workbook book = Workbook.getWorkbook(target);
				if (book != null) {
					List<CustomerOrder> orders = new ArrayList<CustomerOrder>();
					CustomerOrder order;
					CustomerOrderShippingAddress address;
					int sheetNo = book.getNumberOfSheets();
					for (int i = 0; i < sheetNo; i++) {
						Sheet sheet = book.getSheet(i);
						int rowNum = sheet.getRows();
						// int colNum = sheet.getColumns();
						// 第一行是标题头
						for (int r = 1; r < rowNum; r++) { // 行
							order = new CustomerOrder();
							address = new CustomerOrderShippingAddress();
							// 发票号
							String invoiceNO = sheet.getCell(0, r).getContents();
							order.setInvoiceNo(invoiceNO);
							// 交易号
							String tradeNO = sheet.getCell(1, r).getContents();
							order.setTradeNo(tradeNO);
							// 收货人名字
							String firstName = sheet.getCell(2, r).getContents();
							address.setCustomerFirstName(firstName);
							// 收货人姓氏
							String lastName = sheet.getCell(3, r).getContents();
							address.setCustomerLastName(lastName);
							// 收货人电话
							String phone = sheet.getCell(4, r).getContents();
							address.setCustomerPhone(phone);
							// 运输方式
							String shipType = sheet.getCell(5, r).getContents();
							order.setShippingType(shipType);
							// 国家
							String country = sheet.getCell(6, r).getContents();
							address.setCustomerCountry(country);
							// 省/州
							String state = sheet.getCell(7, r).getContents();
							address.setCustomerState(state);
							// 城市
							String city = sheet.getCell(8, r).getContents();
							address.setCustomerCity(city);
							// 街道1
							String street1 = sheet.getCell(9, r).getContents();
							address.setCustomerStreet1(street1);
							//街道2
							String street2 = sheet.getCell(10,r).getContents();
							address.setCustomerStreet2(street2);
							// 邮编
							String postCode = sheet.getCell(11, r).getContents();
							address.setCustomerPostcode(postCode);
							int rowLength = sheet.getRow(r).length;
							CustomerOrderProductDetail productDetail;
							List<CustomerOrderProductDetail> productDetails = new ArrayList<CustomerOrderProductDetail>();
							for (int p = 6; p * 2 < rowLength; p++) {
								productDetail = new CustomerOrderProductDetail();
								// 产品标识
								String sku = sheet.getCell(p * 2, r).getContents();
								productDetail.setSupplierProductSku(sku);
								// 产品数量
								String num = sheet.getCell(p * 2+1, r).getContents();
								productDetail.setProductCount(Integer.parseInt(num));
								productDetails.add(productDetail);
							}
							order.setCustomerOrderProductDetails(productDetails);
							order.setCustomerOrderShippingAddress(address);
							orders.add(order);
						}
						customerOrderService.addCustomerOrders(orders);
					}
					book.close();
				}
			} else {
				log.info("只支持CSV和XLS两种格式文件");
				return INPUT;
			}
		} catch (IOException e) {
			log.error("======CustomerOrderAction-->importFile====IOException==={}", e.getMessage());
			return INPUT;
		} catch (BiffException e) {
			log.error("======CustomerOrderAction-->importFile====BiffException==={}", e.getMessage());
			return INPUT;
		} catch (Exception e) {
			log.error("======CustomerOrderAction-->importFile====Exception==={}", e.getMessage());
			return INPUT;
		} finally {

		}
		return SUCCESS;
	}

	public String findCustomerOrderByPaymentStatus() {
		orderList = customerOrderService.findCustomerOrderByPaymentStatus(
				getSession().get(SystemConfig.MERCHANT_ID_SESSION_NAME).toString(), PaymentStatus.paid);
		return SUCCESS;
	}

	@Override
	public CustomerOrderModel getModel() {
		return model;
	}

	public List<CustomerOrder> getOrderList() {
		return orderList;
	}

	public void setOrderList(List<CustomerOrder> orderList) {
		this.orderList = orderList;
	}
}